/**
 * Copyright (c) 2018, 中国电信甘肃万维公司 All rights reserved.
 * 中国电信甘肃万维公司 专有/保密源代码,未经许可禁止任何人通过任何渠道使用、修改源代码.
 * 项目名称 : wxcloud
 *
 * @version V1.0
 */
package cn.xo68.boot.auth.server.token;

import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.validator.AuthorizationCodeValidator;
import org.apache.oltu.oauth2.as.validator.ClientCredentialValidator;
import org.apache.oltu.oauth2.as.validator.PasswordValidator;
import org.apache.oltu.oauth2.as.validator.RefreshTokenValidator;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.validators.OAuthValidator;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 *  令牌请求处理加强
 * @author admin
 * @date 2018/8/2 23:09
 *
 */
public class OAuthTokenRequestExt extends OAuthTokenRequest {

    protected Map<String, TokenRequestCheck> checkers = new HashMap<String, TokenRequestCheck>();

    /**
     * Create an OAuth Token request from a given HttpSerlvetRequest
     *
     * @param request the httpservletrequest that is validated and transformed into the OAuth Token Request
     * @throws OAuthSystemException  if an unexpected exception was thrown
     * @throws OAuthProblemException if the request was not a valid Token request this exception is thrown.
     */
    public OAuthTokenRequestExt(HttpServletRequest request) throws OAuthSystemException, OAuthProblemException {
        super(request);
    }

    @Override
    protected OAuthValidator<HttpServletRequest> initValidator() throws OAuthProblemException, OAuthSystemException {
        validators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);
        validators.put(GrantType.CLIENT_CREDENTIALS.toString(), ClientCredentialValidator.class);
        validators.put(GrantType.AUTHORIZATION_CODE.toString(), AuthorizationCodeValidator.class);
        validators.put(GrantType.REFRESH_TOKEN.toString(), RefreshTokenValidator.class);
        return super.initValidator();
    }

    /**
     * 添加令牌请求核对
     * @param grantType
     * @param tokenRequestCheck
     */
    public void addTokenRequestCheck(GrantType grantType, TokenRequestCheck tokenRequestCheck){
        tokenRequestCheck.setOAuthTokenRequest(this);
        this.checkers.put(grantType.toString(),tokenRequestCheck);
    }


    /**
     * 审核令牌申请请求
     * @return
     * @throws OAuthProblemException
     */
    public TokenRequestCheckedResult check() throws OAuthProblemException {
        String grantType=this.getGrantType().toLowerCase();
        TokenRequestCheck tokenRequestCheck=checkers.get(grantType);
        if(tokenRequestCheck!=null){
           return tokenRequestCheck.check();
        }else {
            throw OAuthProblemException.error("不支持此模式");
        }
    }
}
